package com.lancer.cloud.generator.controller;

import com.lancer.cloud.common.annotation.OperationLog;
import com.lancer.cloud.common.constants.ServiceNameConstants;
import com.lancer.cloud.common.response.ApiResponse;
import com.lancer.cloud.generator.model.dto.BuildConfigDto;
import com.lancer.cloud.generator.model.query.TableInfoQuery;
import com.lancer.cloud.generator.service.SysGenerationService;
import com.lancer.cloud.generator.service.TableInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 代码生成接口控制类
 *
 * caijinbang
 * @date 2019-06-16 15:06
 */
@Controller
@Api(value = "代码生成controller", tags = {"代码生成接口管理"})
public class SysGenerationController {

    private static final String MODULE_NAME = "代码生成模块";


    @Autowired
    private TableInfoService tableInfoService;

    @Autowired
    private SysGenerationService sysGenService;

    @ApiOperation(value = "分页查询数据库中所有的表信息", notes = "分页查询数据库中所有的表信息", httpMethod = "GET")
    @ApiImplicitParam(name = "query", value = "表信息查询条件", required = false, dataType = "TableInfoQuery")
    @ResponseBody
    @GetMapping("/table/page")
    public ApiResponse<TableInfoQuery> page(TableInfoQuery query){
        return new ApiResponse<>(tableInfoService.findPageByCondition(query));
    }


    @OperationLog(serviceId = ServiceNameConstants.LANCER_GEN_SERVICE, moduleName = MODULE_NAME, actionName = "根据表名称生成代码  返回zip包")
    @ApiOperation(value = "根据表名称生成代码", notes = "根据表名称生成代码  返回zip包", httpMethod = "POST")
    @ApiImplicitParam(name = "buildConfigDto", value = "表配置", required = true, dataType = "BuildConfigDto")
    @PostMapping("/code")
    public void code(@RequestBody BuildConfigDto buildConfigDto, HttpServletResponse response) throws IOException {
        byte[] data = sysGenService.genCodeByTableName(buildConfigDto);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
